﻿package {
	import flash.net.*;
    import flash.media.Sound;;
    import flash.net.URLRequest;
    import flash.media.SoundChannel;
	import flash.events.*;
	public class Player{
		
		private var playlist:Array;
		private var trackNumber:int;
		private var pl:Playlist; //objekt der styrer XML filen
		
		private var playSlider:PlaySlider;
		
		private var playPos:int;
		private var playLenght:int;
		private var playStatus:Boolean;
		
		private var snd:Sound;
		private var channel:SoundChannel;
		
		private var musicLoadedFunction:Function;
	
		public function Player(pl:Playlist){
			this.pl = pl;
			pl.setPlayer(this);
			trackNumber = 0;
			channel = new SoundChannel();
		}
		
		public function setLoadCompleteListener(c:Function){
			this.musicLoadedFunction = c;
		}
		
		public function load() {
			channel.stop();
			trace("");
			playlist = pl.playlist();
			var playSource:URLRequest = new URLRequest(pl.getFilePath(playlist[trackNumber]));
			snd = new Sound(playSource);
			snd.addEventListener(IOErrorEvent.IO_ERROR,function(ev:IOErrorEvent):void{trace("ERRORERROR");});
			snd.addEventListener(Event.COMPLETE, function(ev:Event)
										{
											musicLoadedFunction();   
										});
		}
		
		public function playMusic():Number{
			channel = snd.play();
			channel.addEventListener(Event.SOUND_COMPLETE, function(ev:Event):void 
										{
											nextTrack();
										});
			return snd.length / 1000;
		}
		
		public function stopPlayer() {
			channel.stop();
		} 
		
		public function nextTrack() {
			if(trackNumber < playlist.length - 1)
				trackNumber++;
			else
				trackNumber = 0;
			//return playMusic();
		}
		
		public function previousTrack() {
			if(trackNumber == 0)
				trackNumber = playlist.length - 1;
			else
				trackNumber -= 1;
			//return playMusic();
		}
	}	
}